package com.ptp.backendcertms.networksecurity.filter.exception;

import com.ptp.backendcertms.api.internal.exception.SystemException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 过滤器异常捕捉
 */
@Slf4j
public class ExceptionFilter implements Filter {
    /**
     * 过滤器的异常拦截无法直接使用全局异常拦截器，故先转发至异常控制器后返回异常信息
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            HttpServletRequest req = (HttpServletRequest) servletRequest;
            String servletPath = req.getServletPath();
            if (servletResponse.isCommitted()) {
                log.warn("[ExceptionFilter]-捕捉到过滤器异常，url:{},由于重复提交导致,不再转发至异常控制器", servletPath, e);
                return;
            }
            if (e instanceof SystemException) {
                log.warn("[ExceptionFilter]-捕捉到过滤器异常,请及时处理,url:{},msg:{}", servletPath, e.getMessage());
            } else {
                log.warn("[ExceptionFilter]-捕捉到过滤器异常,请及时处理,url:{}", servletPath, e);
            }
            servletRequest.setAttribute("filter.error", e);
            // 转发到异常控制器
            servletRequest.getRequestDispatcher("/cms/filterException").forward(servletRequest, servletResponse);
        }
    }
}
